package dry.example.utils;


import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author zc
 */
public class RequestWrapperUtil extends HttpServletRequestWrapper {

    private byte[] body;

    private boolean open = false;

    public RequestWrapperUtil(HttpServletRequest request) {
        super(request);
        try {
            this.body = StreamUtil.readStream(request.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ServletInputStream getInputStream() {
        if (open) {
            throw new IllegalStateException("can not re-open input stream");
        }
        open = true;
        return new ServletInputStream() {

            private int offset = 0;

            @Override
            public boolean isFinished() {
                return offset >= body.length;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {
            }

            @Override
            public int read() {
                if (offset >= body.length) {
                    return -1;
                }
                int n = body[offset] & 0xff;
                offset++;
                return n;
            }
        };
    }

    @Override
    public BufferedReader getReader() {
        if (open) {
            throw new IllegalStateException("can not re-open input stream");
        }
        open = true;
        return new BufferedReader(new InputStreamReader(getInputStream(), StandardCharsets.UTF_8));
    }

    public String getBody() {
        return new String(this.body);
    }

}
